import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';

import '../index.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _unameController = TextEditingController();
  final TextEditingController _pwdController = TextEditingController();
  bool pwdShow = false;
  final GlobalKey _formKey = GlobalKey<FormState>();
  bool _nameAutoFocus = true;

  @override
  void initState() {
    // 自动填充上次登录的用户名，填充后将焦点定位到密码输入框
    Debug.info("最后登录用户  ${Global.profile.user?.userName}");
    Debug.info("最后登录用户  ${Global.profile.lastLogin}");
    _unameController.text = Global.profile.lastLogin ?? "";
    if (_unameController.text.isNotEmpty) {
      _nameAutoFocus = false;
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var s = S.of(context);
    var darkModel = Provider.of<DarkModel>(context);
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: AppBar(
              title: Text(s.login),
              centerTitle: true,
              backgroundColor: Colors.transparent,
              systemOverlayStyle: darkModel.isDark(context)
                  ? SystemUiOverlayStyle.light
                  : SystemUiOverlayStyle.dark,
            ),
            floatingActionButton: !Global.isRelease
                ? IconButton(
                    icon: const Icon(Icons.bug_report),
                    onPressed: () =>
                        Navigator.pushNamed(context, "domainSettingsPage"),
                  )
                : null,
            body: _bodyView(s)),
      ),
    );
  }
  var _obscure = true;
  Widget _bodyView(s) {
    return SingleChildScrollView(
      child: Column(
        children: [
          Container(
              margin: const EdgeInsets.only(top: 20, bottom: 54),
              child: Column(
                children: [
                  Center(
                    child: Image.asset('images/me_logo.png',
                        width: 80, height: 80),
                  ),
                  const Center(
                    child: Text('运维管理',
                        style: TextStyle(fontSize: 20),
                        textAlign: TextAlign.center),
                  ),
                ],
              )),
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                _inputView('me_username', _unameController, false, '请输入手机号/账号', 15,
                    (value) {}),
                const SizedBox(height: 20),
                _inputView('me_password', _pwdController, _obscure, '请输入密码', 20, (value) {}),
                const SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    GestureDetector(
                        child: Text(
                          '忘记密码?',
                          style: Theme.of(context)
                              .textTheme
                              .bodyMedium
                              ?.copyWith(color:Theme.of(context).colorScheme.primary),
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, "forgetPassword");
                        })
                  ],
                ),
                const SizedBox(height: 30),
                SizedBox(
                  width: double.infinity,
                  child: CommonButton.elevatedButton(context, text: "登录",
                      onPressed: () {
                    if (!_unameController.text.isNotEmpty ||
                        !_pwdController.text.isNotEmpty) {
                      showToast("请填写账号、密码");
                      return;
                    }
                    _onLogin();
                  }),
                )
              ],
            ),
          ),
        ],
      ),
    );

    //   Padding(
    //   padding: const EdgeInsets.all(16.0),
    //   child: Form(
    //     key: _formKey,
    //     autovalidateMode: AutovalidateMode.onUserInteraction,
    //     child: Column(
    //       children: <Widget>[
    //         TextFormField(
    //             autofocus: _nameAutoFocus,
    //             controller: _unameController,
    //             decoration: InputDecoration(
    //               labelText: s.userName,
    //               hintText: s.userName,
    //               prefixIcon: const Icon(Icons.person),
    //             ),
    //             // 校验用户名（不能为空）
    //             validator: (v) {
    //               return v == null || v.trim().isNotEmpty
    //                   ? null
    //                   : s.userNameRequired;
    //               // return v!.trim().isNotEmpty ? null : s.userNameRequired;
    //             }),
    //         TextFormField(
    //           controller: _pwdController,
    //           autofocus: !_nameAutoFocus,
    //           decoration: InputDecoration(
    //               labelText: s.password,
    //               hintText: s.password,
    //               prefixIcon: const Icon(Icons.lock),
    //               suffixIcon: IconButton(
    //                 icon: Icon(pwdShow
    //                     ? Icons.visibility_off
    //                     : Icons.visibility),
    //                 onPressed: () {
    //                   setState(() {
    //                     pwdShow = !pwdShow;
    //                   });
    //                 },
    //               )),
    //           obscureText: !pwdShow,
    //           //校验密码（不能为空）
    //           validator: (v) {
    //             return v == null || v.trim().isNotEmpty
    //                 ? null
    //                 : s.passwordRequired;
    //             // return v!.trim().isNotEmpty ? null : s.passwordRequired;
    //           },
    //         ),
    //         Padding(
    //           padding: const EdgeInsets.only(top: 25),
    //           child: ConstrainedBox(
    //             constraints: const BoxConstraints.expand(height: 55.0),
    //             child: ElevatedButton(
    //               onPressed: _onLogin,
    //               child: Text(
    //                 s.login,
    //               ),
    //             ),
    //           ),
    //         ),
    //         const SizedBox(height: 20),
    //         Row(
    //           mainAxisAlignment: MainAxisAlignment.end,
    //           children: [
    //             GestureDetector(
    //                 child: const Text('忘记密码',
    //                     style: TextStyle(color: Colors.blue)),
    //                 onTap: () {
    //                   Navigator.pushNamed(context, "forgetPassword");
    //                 })
    //           ],
    //         )
    //       ],
    //     ),
    //   ),
  }

  /// 输入框
  /// image 图标地址
  /// controller控制器
  /// obscure 是否为密码框
  /// name输入框名称
  /// fn回调
  Widget _inputView(image, controller, obscure, name, formatter, fn) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.only(left: 10, top: 0, right: 10, bottom: 0),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.background,
          borderRadius: BorderRadius.circular(8.0),
          boxShadow: [
            BoxShadow(
                color: Theme.of(context).colorScheme.onSurface,
                blurRadius: 6.67,
                spreadRadius: 0.33)
          ]),
      child: Row(
        children: [
          Image.asset('images/$image.png', width: 20, height: 20),
          const SizedBox(width: 10),
          Flexible(
            child: TextField(
              controller: controller,
              obscureText: obscure,
              decoration: InputDecoration(
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
                hintText: name,
                border: const OutlineInputBorder(borderSide: BorderSide.none),
            ),
            inputFormatters: <TextInputFormatter> [
              LengthLimitingTextInputFormatter(formatter)
            ],
            onChanged: (value) {
              fn(value);
            },
          )),
          const SizedBox(width: 10),
          image == 'me_password' ? IconButton(
            icon: Image.asset('images/${!pwdShow ? 'common_psd_is' : 'common_psd'}.png', width: 20, height: 14), onPressed: () {
              setState(() {
                pwdShow = !pwdShow;
                _obscure = !_obscure;
              });
            },
          ) : const SizedBox(width: 1)
        ],
      ),
    );
  }

  void _onLogin() async {
    // 先验证各个表单字段是否合法
    // if ((_formKey.currentState as FormState).validate()) {
    showLoading(context);
    User? user;
    try {
      ResponseData<User> responseData =
          await Api(context).login(_unameController.text, _pwdController.text);
      if (responseData.success) {
        user = responseData.dataModel;
      } else {
        showToast(responseData.msg);
      }
    } on DioError catch (e) {
      //登录失败则提示
      showToast(S.of(context).networkError);
    } finally {
      // 隐藏loading框
      Navigator.of(context).pop();
    }
    if (user != null) {
      // 缓存数据 成功之后跳转
      // 跳转至首页
      Navigator.canPop(context)
          ? Navigator.pop(context)
          : Navigator.pushReplacementNamed(context, "init_data");
    }
    // }
  }
}
